#include "stdafx.h"
#include "fonts.h"

#include <gtl/io/app_path.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

namespace gtl
{

namespace skins
{

fonts::fonts()
{
}

fonts::~fonts()
{
	for(size_t i = 0; i < m_fonts.size(); ++i)
	{
		m_fonts[i].second->DeleteObject();
		delete m_fonts[i].second;
	}
	m_fonts.clear();
}

unsigned int fonts::initialize(gtl::xml& node, wnd* parent_wnd)
{
	HWND hwnd = GetDesktopWindow();
	HDC  hdc  = GetDC(hwnd);
	int ypixel = GetDeviceCaps(hdc, LOGPIXELSY);
	ReleaseDC(hwnd, hdc);

	const gtl::xml::nodes_type& nodes = node.nodes();
	gtl::xml::const_iterator first = nodes.begin();
	gtl::xml::const_iterator last  = nodes.end();
	for(; first != last; ++first)
	{
		const gtl::xml& node = *(*first);
		if(node.tag() != _T("font"))
			continue;

		CFont* font = new CFont;
		gtl::tstr id = node.attrib(_T("id"), true);
		m_fonts.push_back(std::make_pair(id, font));

		int size = node.attrib(_T("size"), true);
		int weight = node.attrib(_T("weight"), true);
		gtl::tstr face = node.attrib(_T("face"), true);

		LOGFONT lf = {0};
		lf.lfItalic = (bool)node.attrib(_T("italic"), true);
		lf.lfUnderline = (bool)node.attrib(_T("underline"), true);
		lf.lfHeight = -MulDiv(size, ypixel, 72);
		if(weight != 0)
			lf.lfWeight = weight;
		if(!face.empty())
			_tcscpy(lf.lfFaceName, face);

		font->CreateFontIndirect(&lf);
	}

	return pane::initialize(node, parent_wnd);
}

font* fonts::get_font(const gtl::tstr& name)
{
	for(size_t i = 0; i < m_fonts.size(); ++i)
	{
		if(name.icmp(m_id + _T(".") + m_fonts[i].first))
			return m_fonts[i].second;
	}

	return NULL;
}

} // end of namespace skins

} // end of namespace gtl